package br.pucrs.prototipoonline.dao;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.StringTokenizer;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;


/**
 * 
 * @author Ricardo Luckei
 * @author Gelson Gentil
 *
 */
public class BaseDAO {
	private static Logger logger = Logger.getLogger(BaseDAO.class);
	
	protected void populateVO(ResultSet rs, Object obj) {
		logger.debug("Entrando");
		try {
			ResultSetMetaData metadata = rs.getMetaData();
			
			int tot = metadata.getColumnCount();
			for (int i = 1; i <= tot; i++) {
				String column = convertColumnName2Bean(metadata.getColumnName(i).toLowerCase());
				Object colValue = rs.getObject(i);
				//logger.debug(column + "=" +colValue);
				BeanUtils.setProperty(obj, column, colValue);
			}
		} catch (Exception e) {
			logger.error("Erro populando o bean", e);
		}
	}
	
	protected Collection populateCollection(ResultSet rs, Class className) {
		Collection ret = new ArrayList();
		try {
			
			
			while(rs.next()) {
				Object obj = className.newInstance();
				populateVO(rs, obj);
				ret.add(obj);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}		
		return ret;
	}
	
	
	private String convertColumnName2Bean(String columnName) {
		if(columnName.indexOf("_")!=-1) {
			String ret = "";
			StringTokenizer tk = new StringTokenizer(columnName, "_");
			while(tk.hasMoreTokens()) {
				if("".equals(ret)) {
					ret=tk.nextToken().toLowerCase();
				} else {
					ret+=StringUtils.capitalize(tk.nextToken());
				}
			}
			return ret;
		} else {
			return columnName;
		}
	}
}
